<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="客户编码" prop="customerId">
        <el-input v-model="queryParams.customerId" placeholder="请输入客户编码" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"
        /></el-form-item>
      <el-form-item label="客户昵称" prop="customerNickname">
        <el-input v-model="queryParams.customerNickname" placeholder="请输入客户昵称" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>

      <el-form-item label="日期">
        <el-date-picker
          v-model="queryParams.effectiveDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="选择日期"
          @change="handleQuery"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="主费用项" prop="mainItem">
        <el-select
          v-model="queryParams.mainItem"
          placeholder="请选择主费用项"
          clearable
          style="width: 240px"
          @change="handleQuery">
          <el-option
            v-for="item in mainItemOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="子费用项" prop="subItem">
        <el-input v-model="queryParams.subItem" placeholder="请输入子费用项" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="searchReset">重置</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:role:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:role:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:role:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:role:remove']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleImportInsert"
          v-hasPermi="['system:role:edit']"
        >报价(走顾师傅的程序的)
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:role:edit']"
        >报价(一年就几次的)
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" prop="id" width="250" v-if="false"/>
      <el-table-column label="客户编码" prop="customerId"/>
      <el-table-column label="客户昵称" prop="customerNickname"/>
      <el-table-column label="生效日期" prop="effectiveDate" :formatter="formatDate" />
      <el-table-column label="主费用项" prop="mainItem"/>
      <el-table-column label="子费用项" prop="subItem"/>
      <el-table-column label="描述" prop="description"/>
      <el-table-column label="范围" prop="scope"/>
      <el-table-column label="单价" prop="price"/>
      <el-table-column label="单位" prop="unit"/>
      <el-table-column label="计费说明" prop="comments"/>
    </el-table>
    <!-- 新增库内信息 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body @close="cancel">
      <el-form ref="form" :model="form"  label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户编码" prop="customerId">
              <el-input v-model="form.customerId" placeholder="请输入客户编码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户昵称" prop="customerNickname">
              <el-input v-model="form.customerNickname" placeholder="请输入客户昵称" />
            </el-form-item>
          </el-col>


        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="日期">
              <el-date-picker
                v-model="form.effectiveDate"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主费用项" prop="mainItem">
              <el-select v-model="form.mainItem" placeholder="请选择主费用项">
                <el-option
                  v-for="item in mainItemOptions"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="子费用项" prop="subItem">
              <el-input v-model="form.subItem" placeholder="请输入子费用项" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="描述" prop="description">
              <el-input v-model="form.description" placeholder="请输入描述" />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="范围" prop="scope">
              <el-input v-model="form.scope" placeholder="请输入范围" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单价" prop="price">
              <el-input v-model="form.price" placeholder="请输入单价" />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计费说明" prop="comments">
              <el-input v-model="form.comments" placeholder="请输入计费说明" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入报价 新增-->
    <el-dialog :title="uploadInsert.title" :visible.sync="uploadInsert.open" width="400px" append-to-body>
      <el-upload
        ref="uploadInsertRef"
        multiple
        accept=".xlsx, .xls"
        :headers="uploadInsert.headers"
        :action="uploadInsert.url + '?updateSupport=' + uploadInsert.updateSupport"
        :disabled="uploadInsert.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="(res, file, list) => handleFileSuccess(res, file, list, 'insert')"
        :on-error="(err, file, list) => handleError(err, file, list, 'insert')"
        :auto-upload="false"
        drag
        name="files"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击选择多个文件</em></div>
      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm('insert')" :loading="uploadInsert.isUploading">确 定</el-button>
        <el-button @click="cancelUpload('insert')">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 导入报价 不带新增 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        multiple
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="(res, file, list) => handleFileSuccess(res, file, list, 'normal')"
        :on-error="(err, file, list) => handleError(err, file, list, 'normal')"
        :auto-upload="false"
        drag
        name="files"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击选择多个文件</em></div>
      </el-upload>

      <el-progress
        v-if="uploadProgress > 0"
        :percentage="uploadProgress"
        :stroke-width="18"
        status="success"
        style="margin-top: 15px;"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm('normal')" :loading="upload.isUploading">确 定</el-button>
        <el-button @click="cancelUpload('normal')">取 消</el-button>
      </div>
    </el-dialog>




    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>

</template>

<script>

import {getList,addOrUpdate,deleteByIds,exportByIds} from '@/api/amac/inWareHouse/inWareHouse'
import { getToken } from '@/utils/auth'

export default {
  name: "Role",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      pictureDetails: false,  // 控制弹窗显示
      srcList: [],  // 存储图片路径的数组
      currentIndex: 0,  // 当前显示图片的索引
      // 菜单列表
      menuOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerNickname:undefined,
        customerId:undefined,
        effectiveDate:undefined,
        mainItem:undefined,
        subItem:undefined,

      },
      dialogImageUrl: '',
      dialogVisible: false,
      // 图片数量限制
      limit: 3,
      //图片地址
      imageUrl: "",
      // 表单参数
      // 表单参数
      form: {},
      // ... existing data properties ...
      selectedMonth: '', // 当前选择的月份
      submitting: false, // 控制提交按钮的加载状态
      mainItemOptions: ['一、入库卸货费', '二、TOC订单处理费', '三、仓储费','四、TOB转运订单收费项','五、退货入库','六、增值服务'],
      uploadFiles: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/amac/contract/uploadExcel'
      },
      uploadInsert: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/amac/contract/uploadExcelInsert'
      },
      uploadProgress: 0,
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    // 🔽 页面加载时自动调用
  },
  methods: {
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        customerNickname: undefined,
        customerId: undefined,
        effectiveDate: undefined,
        mainItem: undefined,
        subItem: undefined,
        scope: undefined,
        description: undefined,
        price: undefined,
        unit: undefined,
        comments: undefined,
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList();
    },
    /** 重置按钮操作 */
    searchReset() {
      this.queryParams.pageNum = 1
      this.queryParams = {}
      this.getList();
    },
    /** 查询列表 */
    // 日期格式化
    formatDate(row, column, cellValue) {
      if (!cellValue) return '';
      return cellValue.slice(0, 10); // 只取 yyyy-MM-dd
    },
    getList() {
      getList(this.queryParams).then(response => {
        console.log("11111",response)
        if (!response.rows) return false
        this.roleList = response.rows
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    handleAdd(){
      this.open = true;
      this.title = "新增库内信息";
    },
    handleUpdate(){
      const selected = this.roleList.find(item => item.id === this.ids[0]);
      if (!selected) return;

      this.form = { ...selected };  // 深拷贝到表单
      this.title = "修改库内信息";
      this.open = true;
    },
    handleDelete(){
      this.$confirm("确定要删除选中的数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteByIds(this.ids).then(res => {
          this.$message.success("删除成功");
          this.getList();
        }).catch(() => {
          this.$message.error("删除失败");
        });
      }).catch(() => {
        // 用户点击取消
      });
    },
    handleExport(){
      const obj = { ids: this.ids}
      this.download('/amac/inWareHouse/export',obj , `库内报价${new Date().getTime()}.xlsx`)
      exportLoading: false
    },
    /**
     * 新增和修改的确认按钮
     */
    submitForm() {
      this.submitting = true;
      console.log("this.form.id", this.form.id);

      addOrUpdate(this.form)  // 不管是新增还是修改，统一走这个方法
        .then(res => {
          this.$message.success(this.form.id ? "修改成功" : "新增成功");
          this.open = false;
          this.getList();
        })
        .finally(() => {
          this.submitting = false;
        });
    },
    //---------------报价导入
    /** 导入按钮操作 带新增*/
    handleImportInsert() {
      this.uploadInsert.title = '报价导入(带新增)'
      this.uploadInsert.open = true
    },
    /** 打开导入弹窗 */
    handleImport(type) {
      if (type === 'insert') {
        this.uploadInsert.title = '报价导入(带新增)';
        this.uploadInsert.open = true;
      } else {
        this.upload.title = '报价导入';
        this.upload.open = true;
      }
    },
    /** 上传成功 */
    handleFileSuccess(response, file, fileList, type) {
      const target = type === 'insert' ? this.uploadInsert : this.upload;
      const refName = type === 'insert' ? 'uploadInsertRef' : 'upload';
      const ref = this.$refs[refName];

      target.isUploading = false;
      this.loading = false;
      this.uploadProgress = 100;
      target.open = false;

      if (ref) ref.clearFiles();

      this.$alert(
        `<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>${response.msg}</div>`,
        '导入结果',
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    /** 通用提交上传 */
    submitFileForm(type) {
      const target = type === 'insert' ? this.uploadInsert : this.upload;
      const refName = type === 'insert' ? 'uploadInsertRef' : 'upload';
      const ref = this.$refs[refName];

      if (!ref || ref.uploadFiles.length === 0) {
        this.$message.warning("请先选择文件！");
        return;
      }
      this.uploadProgress = 0;   // 重置进度条
      this.loading = true;
      target.isUploading = true;
      ref.submit();
    },
    /** 上传中 */
    handleFileUploadProgress(event, file, fileList) {
      if (fileList.length > 0) {
        let total = fileList.reduce((sum, f) => sum + (f.percentage || 0), 0);
        this.uploadProgress = Math.floor(total / fileList.length);
      }
    },
    /** 上传失败 */
    handleError(err, file, fileList, type) {
      const target = type === 'insert' ? this.uploadInsert : this.upload;
      target.isUploading = false;
      this.loading = false;
      this.uploadProgress = 0;
      this.$message.error("上传失败：" + err);
    },

    /** 取消上传并清空文件 */
    cancelUpload(type) {
      const target = type === 'insert' ? this.uploadInsert : this.upload;
      const refName = type === 'insert' ? 'uploadInsertRef' : 'upload';
      const ref = this.$refs[refName];

      target.open = false;
      target.isUploading = false;
      this.loading = false;

      if (ref) ref.clearFiles();
    }
  },
};
</script>
